/* eslint-disabed */
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import Top from '@/components/Top/Top.vue';
import {
  getImgToken,
  getSelectByMenuId,
  getWorks,
  searchRefrigeratorById,
  submitMenuIdList,
  submitRefrigerator,
} from '@/services/review';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import type {
  RequestMenuIdList,
  ResponseWorksData,
  ResultOutList,
  ReviewRefrigeratorList,
  selectByMenuId,
} from '@/services/types/review';
import { formatDateFromTimestamp } from '@/utils/utils';
import type { Data } from '@/utils/http';
import { useMemberStore } from '@/stores/modules/member';
// 高亮的下标
const activeIndex = ref(0);
const subTypes = ref(['表格审批', '任务']);
// 表格审批
const myReview = () => {
  // 审批
  const completeStatus = ref([
    {
      text: '未审批',
      value: 1,
    },
    {
      text: '已审批',
      value: 2,
    },
  ]);
  // 任务
  const unionMenu = ref([
    {
      value: '0',
      text: '全部',
    },
    {
      value: '8285824675708862464',
      text: '热食和冷食',
    },
    {
      value: '8286263252886290432',
      text: '食物冷却',
    },
    {
      value: '8286263745347911680',
      text: '温度计校准',
    },
    {
      value: '8286263825078222848',
      text: '添加剂使用',
    },
    {
      value: '8286263942992691200',
      text: '食品留样',
    },
    {
      value: '8286264035435151360',
      text: '添加剂清单',
    },
    {
      value: '8286264342009413632',
      text: '时间控制',
    },
    {
      value: '8286264836236836864',
      text: '消毒液更换',
    },
    {
      value: '8286265006328446976',
      text: '紫外灯',
    },
    {
      value: '8286266087871676416',
      text: '果蔬消毒',
    },
  ]);
  // 表格审批
  const formDataTable = ref<{
    time: Date[];
    completeStatus: number;
    unionMenu: string;
  }>({
    time: [new Date(new Date().setDate(new Date().getDate() - 7)), new Date()],
    completeStatus: 1,
    unionMenu: '0',
  });
  const selectReviewList = async () => {
    enum Tasks {
      '热食和冷食' = '8285824675708862464',
      '食物冷却' = '8286263252886290432',
      '温度计校准' = '8286263745347911680',
      '添加剂使用' = '8286263825078222848',
      '食品留样' = '8286263942992691200',
      '添加剂清单' = '8286264035435151360',
      '时间控制' = '8286264342009413632',
      '消毒液更换' = '8286264836236836864',
      '紫外灯' = '8286265006328446976',
      '果蔬消毒' = '8286266087871676416',
    }
    const data = ref<selectByMenuId>({
      beginTime: formatDateFromTimestamp(Number(formDataTable.value.time[0])),
      endTime: formatDateFromTimestamp(Number(formDataTable.value.time[1])),
      unionMenuId: formDataTable.value.unionMenu,
      completeStatus: formDataTable.value.completeStatus,
    });

    try {
      // 如果是全部,需要遍历操作
      if (formDataTable.value.unionMenu === '0') {
        const promises: Promise<Data<ResultOutList[]>>[] = [];
        // 遍历操作
        for (const task in Tasks) {
          data.value.unionMenuId = Tasks[task as keyof typeof Tasks];
          promises.push(getSelectByMenuId(data.value));
        }

        return Promise.all(promises.map((p) => p.then((res) => res.data)));
      } else {
        const res = await getSelectByMenuId(data.value);
        if (res) {
          return [res.data];
        }
      }
    } catch (error) {
      console.log(error);
    }
  };
  return {
    completeStatus,
    unionMenu,
    formDataTable,
    selectReviewList,
  };
};
const { completeStatus, unionMenu, formDataTable, selectReviewList } =
  myReview();
// 任务
const myTask = () => {
  // 0全部状态 1待提交，2待审核
  const workStatus = ref([
    {
      text: '全部状态',
      value: 0,
    },
    {
      text: '待提交',
      value: 1,
    },
    {
      text: '待审核',
      value: 2,
    },
    {
      text: '已审核',
      value: 4,
    },
  ]);
  const tasks = ref([
    {
      text: '任务审核',
      value: 0,
    },
    {
      text: '今日工作清单',
      value: 1,
    },
  ]);
  const taskFormData = ref<{
    workStatus: number;
    tasks: number;
  }>({
    workStatus: 0,
    tasks: 0,
  });
  // 任务审核
  const taskReviewData = async () => {
    const res = await searchRefrigeratorById(taskFormData.value.workStatus);
    if (res) {
      return res;
    }
  };
  // 今日工作清单
  const taskListData = async () => {
    const res = await getWorks();
    if (res) {
      return res;
    }
  };
  return {
    workStatus,
    tasks,
    taskFormData,
    taskReviewData,
    taskListData,
  };
};
const { workStatus, tasks, taskFormData, taskReviewData, taskListData } =
  myTask();
// 审核一键提交
const review = () => {
  reviewList.value.map((item) => {
    const data = ref<RequestMenuIdList>({
      id: item.id, //BigInt(item.id).toString(), // eslint-disable-line
    });
    submitMenuIdList(data.value).then((res) => {
      if (res.data === 'success') {
        uni.showToast({
          title: '提交成功!',
          icon: 'none',
        });
      }
    });
  });
  // 更新页面数据
  getReviewList();
};
// 冰箱一键提交按钮
const task = () => {
  taskReview.value.map((item) => {
    if (item.workStatus !== 4) {
      submitRefrigerator(item.id).then((res) => {
        if (res.data === 'success') {
          uni.showToast({
            title: '提交成功!',
            icon: 'none',
          });
        }
      });
    }
  });
  // 更新页面数据
  getTaskReviewData();
};
//任务数据
const taskReview = ref<ReviewRefrigeratorList[]>([]);
// 审核列表数据
const reviewList = ref<ResultOutList[]>([]);
// 今日工作清单
const taskList = ref<ResponseWorksData[]>([]);
// 页面加载
onShow(async () => {
  // 获取sessionId
  const session = useMemberStore().getProfile()!;
  const imgToken = (await getImgToken()).data.token;
  if (imgToken) {
    useMemberStore().setProfile({
      ...session,
      imgToken,
    });
  }
  getReviewList();
  // 任务审核
  getTaskReviewData();
});
// 下拉刷新
onPullDownRefresh(() => {
  // 其他审核
  getReviewList();
  // 任务审核
  getTaskReviewData();
  uni.stopPullDownRefresh();
});

// 切换审核状态
const changeWorkStatus = (e: number) => {
  taskFormData.value.workStatus = e;
  getTaskReviewData();
};
// 切换表格类型
const changeUnionMenu = (e: string) => {
  formDataTable.value.unionMenu = e;
  getReviewList();
};
// 切换时间
const changeTime = (e: []) => {
  formDataTable.value.time = e;
  getReviewList();
};
// 获取任务数据
const getTaskReviewData = () => {
  uni.showLoading({
    title: '获取数据中...',
  });
  // 冰箱
  taskReviewData().then((res) => {
    console.log('🚀 ~ taskReviewData ~ res:', res);

    if (res) {
      setTimeout(() => {
        taskReview.value = res!;
      }, 1);
    }
  });
  // 今日任务
  taskListData().then((res) => {
    const regex: RegExp = /冰箱记录/;
    if (res) {
      taskList.value = [];
      res.data.map((item) => {
        if (!regex.test(item.name!)) {
          taskList.value.push(item);
        }
      });
    }
  });
  uni.hideLoading();
};
// 获取审核列表数据
const getReviewList = async () => {
  uni.showLoading({
    title: '获取数据中...',
  });
  const res = await selectReviewList();
  reviewList.value = res!.flatMap((obj: any) => obj.resultOutList);
  uni.hideLoading();
};
// 分割名称
const getTitle = (item: ResultOutList) => {
  const matchResult = item.name!.split('$');
  return matchResult ? matchResult[0] : ''; // 如果匹配成功返回匹配的第一个结果，否则返回空字符串
};
const menuList = [
  {
    name: 'A1 每日温度记录-冷食和热食',
    pathName: 'reShiHeLengShi',
  },
  {
    name: 'A2  食物冷却记录',
    pathName: 'shiWuLengQue',
  },
  {
    name: '探针式温度计月度校准记录',
    pathName: 'wenDuJiJiaoZhun',
  },
  {
    name: '食品添加剂使用记录',
    pathName: 'tianJiaJiShiYong',
  },
  {
    name: '食品留样记录',
    pathName: 'shiPinLiuYang',
  },
  {
    name: '食品添加剂使用清单',
    pathName: 'tianJiaJiQingDan',
  },
  {
    name: 'A20 时间作为公共卫生控制手段--即食潜在危险食品',
    pathName: 'shiJianKongZhi',
  },
  {
    name: '消毒液更换记录',
    pathName: 'xiaoDuYeGengHuan',
  },
  {
    name: '紫外灯使用记录',
    pathName: 'ziWaiDeng',
  },
  {
    name: '即食水果&蔬菜清洗消毒记录',
    pathName: 'guoShuXiaoDu',
  },
];
// 点击列表跳转详情
const goTo = (item: ResultOutList) => {
  menuList.map((obj: any) => {
    if (obj.name === getTitle(item)) {
      uni.navigateTo({
        url: `/pages/writePages/${obj.pathName}/${obj.pathName}?id=${BigInt(
          item.id,
        ).toString()}`, // eslint-disable-line
      });
    }
  });
};
onMounted(() => {
  // 小程序分享函数
  // #ifdef MP-WEIXIN
  uni.showShareMenu<{
    withShareTicket: true;
    menus: ('shareAppMessage' | 'shareTimeline')[];
  }>({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline'],
  });
  // #endif
});
</script>
<template>
  <Top />
  <view class="boder">
    <view class="tabs">
      <text
        class="text"
        v-for="(item, index) in subTypes"
        :key="index"
        :class="{ active: index === activeIndex }"
        @tap="activeIndex = index"
      >
        {{ item }}
      </text>
    </view>
    <!-- 表格审批 -->
    <view v-show="activeIndex === 0">
      <view class="heard">
        <uni-forms
          :modelValue="formDataTable"
          label-position="left"
          label-width="90"
        >
          <uni-forms-item label="日期:" required>
            <uni-datetime-picker
              v-if="formDataTable.time[0]"
              type="daterange"
              return-type="timestamp"
              v-model="formDataTable.time"
              :border="true"
              @change="changeTime"
            />
          </uni-forms-item>
          <uni-forms-item label="审批状态：" required>
            <uni-data-checkbox
              v-model="formDataTable.completeStatus"
              :localdata="completeStatus"
              @change="getReviewList()"
            />
          </uni-forms-item>
          <uni-forms-item label="表格类型：" required>
            <uni-data-select
              v-model="formDataTable.unionMenu"
              :localdata="unionMenu"
              @change="changeUnionMenu"
            ></uni-data-select>
          </uni-forms-item>
        </uni-forms>
        <button
          class="bt"
          size="default"
          type="primary"
          :disabled="formDataTable.completeStatus === 2"
          @tap="review"
        >
          一键审批
        </button>
      </view>
      <scroll-view scroll-y class="scroll-view">
        <uni-list>
          <uni-list-item
            v-for="(item, index) in reviewList"
            :key="index"
            :title="getTitle(item)"
            :note="`提交日期:${item.createTime}`"
            clickable
            @click="goTo(item)"
            :rightText="item.status === 1 ? '未审批' : '已审批'"
          ></uni-list-item>
        </uni-list>
      </scroll-view>
    </view>
    <!-- 任务 -->
    <view v-show="activeIndex === 1"
      ><view class="heard">
        <uni-forms
          :modelValue="taskFormData"
          label-position="left"
          label-width="90"
        >
          <uni-forms-item label="审批类型：" required>
            <uni-data-checkbox
              v-model="taskFormData.tasks"
              :localdata="tasks"
            />
          </uni-forms-item>
          <uni-forms-item label="表格状态:" required>
            <uni-data-select
              v-model="taskFormData.workStatus"
              :localdata="workStatus"
              @change="changeWorkStatus"
            ></uni-data-select>
          </uni-forms-item>
        </uni-forms>
        <button
          class="bt"
          size="default"
          type="primary"
          :disabled="taskFormData.tasks === 1"
          @tap="task"
        >
          一键审批
        </button>
      </view>

      <scroll-view scroll-y class="scroll-view">
        <uni-list>
          <view v-if="taskFormData.tasks === 0">
            <view v-for="(itemTask, key) in taskReview" :key="key">
              <uni-list-item
                v-for="(item, index) in itemTask.operatorDataList"
                :key="index"
                :title="`${item.formName ? item.formName : '整改事项'}=>${
                  index === 0 ? '上午' : '下午'
                }`"
                :note="`提交日期:${item.modifyTime}`"
                link
                :to="
                  `/pages/writePages/refrigeratorPage/refrigeratorPage?item=` +
                  encodeURIComponent(JSON.stringify(item))
                "
                :rightText="itemTask.workStatus === 4 ? '已审批' : '未审批'"
              ></uni-list-item>
            </view>
          </view>
          <!-- 今日工作清单 -->
          <view v-if="taskFormData.tasks">
            <uni-list-item
              v-for="(item, index) in taskList"
              :key="index"
              :title="item.title"
              :to="
                `/pages/writePages/tasksPage/tasksPage?item=` +
                encodeURIComponent(JSON.stringify(item))
              "
              link
              :note="item.name"
              :rightText="item.workStatus !== 1 ? '已完成' : '未完成'"
            >
            </uni-list-item>
          </view>
        </uni-list> </scroll-view
    ></view>
  </view>
</template>

<style lang="scss" scoped>
.boder {
  position: relative;
  width: 90%;
  height: calc(80% - var(--window-bottom));
  border: solid 1px #dcdcdc;
  box-shadow: 0 0 5px rgba($color: #d8d8d8, $alpha: 0.5);
  margin: 0 auto;

  .tabs {
    display: flex;
    justify-content: space-evenly;
    height: 100rpx;
    line-height: 90rpx;
    margin: 0 20rpx;
    font-size: 28rpx;
    border-radius: 10rpx;
    box-shadow: 0 4rpx 5rpx rgba(200, 200, 200, 0.3);
    color: #333;
    background-color: #fff;

    z-index: 9;
    .text {
      margin: 0 20rpx;
      position: relative;
    }
    .active {
      &::after {
        content: '';
        width: 40rpx;
        height: 4rpx;
        transform: translate(-50%);
        background-color: #27ba9b;
        position: absolute;
        left: 50%;
        bottom: 24rpx;
      }
    }
  }
  .scroll-view {
    height: 40vh;
    border: solid 1px #b8b8b8;
    border-radius: 10px;
    .navigator {
      margin: 1% auto;
    }
  }
  .heard {
    margin: 1.5625rem 0.625rem;
    border: solid 1px #b8b8b8;
    border-radius: 10px;
    .bt {
      width: 60%;
      border-radius: 10px;
      background-color: #5199ff;
    }
  }
}
::v-deep.uni-list-item__extra-text {
  color: #ff0000;
}
</style>
